package com.zim.access.service.session.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.google.common.base.Preconditions;
import com.zim.access.common.chat.Session;
import com.zim.access.common.page.Page;
import com.zim.access.common.page.QueryOptions;
import com.zim.access.infrastructurre.mybaties.session.SessionMapper;
import com.zim.access.service.session.SessionService;
import com.zim.access.domain.session.SessionConverter;
import com.zim.access.domain.session.SessionDo;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;

import java.util.stream.Collectors;

/**
 * @author hanyue
 * @version 1.0
 * @date 2021/12/27 上午10:18
 */
@Slf4j
public class SessionServiceImpl implements SessionService {

    private final SessionMapper sessionMapper;

    public SessionServiceImpl(SessionMapper sessionMapper) {
        this.sessionMapper = sessionMapper;
    }

    @Override
    public Session findById(String id) {
        Preconditions.checkArgument(StringUtils.isNotBlank(id), "SessionId can't be empty!!!");

        return SessionConverter.toSession(sessionMapper.selectById(id));
    }

    @Override
    public Page<Session> findMay(QueryOptions options, Wrapper<SessionDo> queryWrapper) {
        var selectPage = sessionMapper.selectPage(PageDTO.of(options.getPage(), options.getSize()), queryWrapper);

        var result = new Page<Session>();
        if (selectPage != null &&
                selectPage.getRecords() != null &&
                !selectPage.getRecords().isEmpty()) {

            result.setTotal(selectPage.getTotal());
            result.setList(selectPage.getRecords().stream().map(item -> {
                return SessionConverter.toSession(item);
            }).collect(Collectors.toList()));
        }
        return result;
    }

    @Override
    public Page<Session> searchByUserId(String userId, QueryOptions options) {
        Preconditions.checkArgument(StringUtils.isNotBlank(userId), "UserId can't be empty!!!");

        QueryWrapper<SessionDo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("from_id", userId).or().eq("to_id", userId);
        return findMay(options, queryWrapper);
    }

    @Override
    public Page<Session> searchByUserName(String userName, QueryOptions options) {
        Preconditions.checkArgument(StringUtils.isNotBlank(userName), "UserName can't bt empty!!!");

        QueryWrapper<SessionDo> queryWrapper = new QueryWrapper();
        queryWrapper.like("from_name", userName).or().like("to_name", userName);
        return findMay(options, queryWrapper);
    }

    @Override
    public Session createSession(Session session) {
        Preconditions.checkNotNull(session, "Entity can't be empty!!!");

        sessionMapper.insert(SessionConverter.toSessionDao(session.fillAttribute()));
        return session;
    }

    @Override
    public boolean deleteSession(String id) {
        Preconditions.checkArgument(StringUtils.isNotBlank(id), "SessionId can't be empty!!!");

        try {
            sessionMapper.deleteById(id);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("[{}] sessionId be deleted fail", id, e);
            }

            return false;
        }
        return true;
    }

    @Override
    public boolean updateSession(String id, Session session) {
        Preconditions.checkNotNull(session, "Entity can't be empty!!!");
        Preconditions.checkArgument(StringUtils.isNotBlank(id), "SessionId can't be empty!!!");

        try {
            sessionMapper.updateById(SessionConverter.toSessionDao(session.setId(id)));
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("[{}] sessionId be updated fail", id, e);
            }

            return false;
        }
        return true;
    }

    @Override
    public Long searchUnReadById(String id) {
        Preconditions.checkArgument(StringUtils.isNotBlank(id), "SessionId can't be empty!!!");

        return findById(id).getUnReadCut();
    }

    @Override
    public Long searchAllUnRead() {
        // TODO 指标性数据，从etcd里面获取
        return null;
    }
}
